from elasticsearch import Elasticsearch

es_host = "http://es-cn-27a3mxtqr0003iqw2.public.elasticsearch.aliyuncs.com:9200"
es_username = "elastic"
es_password = "12qwaszxcv@"


class elasticsearch():
    """ 定义查询语句，查询词 ”keywords_title"^6+"keywords_by_syn"^3+"short_by_textrank"
        :index_name: es具体某个索引
        :return: es返回的json字符串
    """
    def __init__(self, index_name):
        self.es = Elasticsearch(
            [es_host],
            http_auth=(es_username, es_password),
            timeout=3600
        )
        self.index_name = index_name


    def search(self, query, level, province, city, source, tag, page, starttime, endtime):
        ds1 = {
            "_source": ["id", "title", "source", "province", "city", "pubDate", "number", "content", "sourceurl"],
            "query": {
                "bool": {
                    "filter": [],
                    "must": [],
                    "should": []
                }
            }
        }

        if query:
            ds1["query"]["bool"]["should"].extend([
                {"match_phrase": {"title_keyword": {"query": query, "boost": 6}}},
                {"match_phrase": {"content_keyword": {"query": query, "boost": 3}}},
                {"match_phrase": {"short_by_content": query}}
            ])
            ds1["query"]["bool"]["filter"].append({"multi_match": {"query": query, "fields": ["title_keyword", "content_keyword", "short_by_content"]}})

        if level:
            level_terms = [{"wildcard": {"level": f"*{c}*"}} for c in level]
            ds1["query"]["bool"]["must"].append({"bool": {"should": level_terms}})
        if province:
            province_terms = [{"wildcard": {"province": f"*{p}*"}} for p in province]
            ds1["query"]["bool"]["must"].append({"bool": {"should": province_terms}})
        if city:
            city_terms = [{"wildcard": {"city": f"*{c[:c.find('市')]}*"}} for c in city]
            ds1["query"]["bool"]["must"].append({"bool": {"should": city_terms}})
        if source:
            source_terms = [{"wildcard": {"source": f"*{s}*"}} for s in source]
            ds1["query"]["bool"]["must"].append({"bool": {"should": source_terms}})
        if tag:
            tag_terms = [{"wildcard": {"tag": f"*{t}*"}} for t in tag]
            ds1["query"]["bool"]["must"].append({"bool": {"should": tag_terms}})
        if starttime:
            ds1["query"]["bool"]["filter"].append({"range": {"pubDate": {"gte": starttime}}})
        if endtime:
            ds1["query"]["bool"]["filter"].append({"range": {"pubDate": {"lte": endtime}}})

        match_data = self.es.search(index=self.index_name, body=ds1, size=400)

        for hit in match_data["hits"]["hits"]:
            content = hit["_source"]["content"]
            hit["_source"]["content"] = content[:200] if content else ""

        return match_data



    def search_by_id(self, query_id):
        ds2 = {
            "query": {
                "match": {
                    "id": query_id
                }
            }
        }
        match_data = self.es.search(index=self.index_name, body=ds2)
        return match_data

